package com.hengtiansoft.lfy.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.chart.action.GetUserJson;
import com.hengtiansoft.lfy.chart.action.RegisterJson;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.hengtiansoft.lfy.chart.applib.utils.HXPreferenceUtils;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.chart.bean.getUserByUsernameBean;
import com.hengtiansoft.lfy.chart.db.UserDao;
import com.hengtiansoft.lfy.chart.domain.FriendsUser;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.entity.TokenInfo;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.ScreenUtils;
import com.hengtiansoft.lfy.utils.Utils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMPushManager;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by daiye on 2016/10/27 0027.
 */

public class RegisterActivityV2 extends BaseActivity {
    private static final String TAG = RegisterActivityV2.class.getSimpleName();
    private final int ACTIVITY_RESULT_REGISTER_MOBILE = 1;

    private ImageView iv_back = null;
    private EditText mUserNameEt;
    private EditText mPasswordEt;
    private EditText mPasswordAgainEt;
    private Button mRegisterBt;
    private boolean progressShow;
    private boolean hasSendJson = false;
    private ProgressDialog pd;
    private String username;
    private String password;
    private RegisterJson mRegisterJson;
    private boolean hasSendTokenJson = false;
    private Context mContext;
    private boolean hasSendGetUserJson = false;
    private boolean updatenick;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        initData();
        initView();
    }

    private void initData(){

    }

    private void initView() {
        pd = new ProgressDialog(RegisterActivityV2.this,
                ProgressDialog.THEME_HOLO_LIGHT);
        pd.setCanceledOnTouchOutside(false);
        setContentView(R.layout.activity_register);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            public final void onClick(View v) {
                finish();
            }
        });

        mUserNameEt = (EditText) findViewById(R.id.username_et);
        mPasswordEt = (EditText) findViewById(R.id.password_et);
        mPasswordAgainEt = (EditText) findViewById(R.id.password_again_et);

        mRegisterBt = (Button)findViewById(R.id.register_bt);
        mRegisterBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) mRegisterBt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mRegisterBt, 0);
                processRegister();
            }
        });

        mPasswordEt.setTypeface(Typeface.DEFAULT);
        mPasswordEt.setTransformationMethod(new PasswordTransformationMethod());
        mPasswordAgainEt.setTypeface(Typeface.DEFAULT);
        mPasswordAgainEt.setTransformationMethod(new PasswordTransformationMethod());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public String userNameStr;
    public String firstPasswordStr;

    private void processRegister() {
        progressShow = true;
        pd.setCancelable(true);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                progressShow = false;
            }
        });
        pd.setMessage(getString(R.string.Is_the_registered));
        // 用户注册信息提交
        userNameStr= mUserNameEt.getText().toString();
        firstPasswordStr = mPasswordEt.getText().toString();
        final String secondPasswordStr = mPasswordAgainEt.getText().toString();

        if(TextUtils.isEmpty(userNameStr) ){
            Toast.makeText(this, R.string.login_username_empty_tips, Toast.LENGTH_SHORT).show();
            return;
        }

        if(TextUtils.isEmpty(firstPasswordStr) ){
            Toast.makeText(this, R.string.login_password_empty_tips, Toast.LENGTH_SHORT).show();
            return;
        }
        if(!firstPasswordStr.equals(secondPasswordStr)){
            Toast.makeText(this, R.string.register_pwd_different_tips, Toast.LENGTH_SHORT).show();
            return;
        }
//        if( firstPasswordStr.length() < 6 ){
//            Toast.makeText(this, R.string.passwd_less6, Toast.LENGTH_SHORT).show();
//            return;
//        }

        registerServer();
        pd.show();
    }

    private void registerServer() {
        mRegisterJson = new RegisterJson(
                mUserNameEt.getText().toString().trim(),
                CommonUtils.MD5(mPasswordEt.getText().toString().trim()),
                null);

        if (!hasSendJson) {
            username = mUserNameEt.getText().toString().trim();
            password = CommonUtils
                    .MD5(mPasswordEt.getText().toString().trim());
            registerRequest(Constants.RegisterUser_URLTEMP, mRegisterJson);
        }
    }
    private void registerRequest(String registerUrl,
                                 RegisterJson mRegisterJson) {
        Log.i(TAG, "<registerRequest>--<onResponse>--上传的JSon数据：  LoginJson = "
                + mRegisterJson);
        hasSendJson = true;
        Type type = new TypeToken<BaseResult>() {
        }.getType();
        JsonListRequest<BaseResult> request = new JsonListRequest<BaseResult>(
                mContext, Request.Method.POST, registerUrl, mRegisterJson.toString(),
                null, null, type, false, new Response.Listener<BaseResult>() {

            @Override
            public void onResponse(BaseResult arg0) {
                Log.i(TAG,
                        "<registerRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                + arg0);
                int code = 1;
                String message = null;
                message = arg0.getMessage();
                code = arg0.getCode();
                Log.i(TAG,
                        "<registerRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                + message);
                Log.i(TAG,
                        "<registerRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                + code);
                if (code == 0) {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                    if (!hasSendTokenJson) {
                       getUserToken();
                    }
                } else {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                    pd.dismiss();
                }
                hasSendJson = false;
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                NetworkResponse response = arg0.networkResponse;
                if (response != null) {
                    try {
                        String json = new String(response.data,
                                HttpHeaderParser.parseCharset(
                                        response.headers));
                        Log.i(TAG,
                                "<registerRequest>--<onErrorResponse> -- json = "
                                        + json);
                        Log.i(TAG,
                                "<registerRequest>--<onErrorResponse> -- response.data = "
                                        + response.data);
                        Log.i(TAG,
                                "<registerRequest>--<onErrorResponse> -- response.headers = "
                                        + response.headers);
                        // showToast(mContext, json,
                        // Toast.LENGTH_SHORT);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                if (arg0 != null && arg0.toString().contains(
                        "com.android.volley.NoConnectionError")) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.ServerError")) {
                    Toast.makeText(mContext,
                            getString(
                                    R.string.service_temporarily_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.TimeoutError")) {
                    Toast.makeText(mContext,
                            getString(R.string.time_out_error),
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext,
                            getString(R.string.request_fail),
                            Toast.LENGTH_SHORT).show();
                }
                Log.i(TAG,
                        "<registerRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                + arg0);
                Log.i(TAG,
                        "<registerRequest>--<onErrorResponse>--服务器请求失败： response = "
                                + response);
                hasSendJson = false;
                pd.dismiss();
            }

        });
        VolleyUtil.addRequest(request);
    }

   /* private void registerServer() {
        NetHelper.userRegister( RegisterActivityV2.this, userNameStr, Utils.MD5(firstPasswordStr.trim()), null,  new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRetcode() == 0) {
                    getUserToken();
                    Toast.makeText(RegisterActivityV2.this, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(RegisterActivityV2.this, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(RegisterActivityV2.this, msg, Toast.LENGTH_SHORT).show();
            }
        }, ServiceResult.class);
    }*/

    private void getUserToken(){
        hasSendTokenJson = true;
        NetHelper.getUserToken( RegisterActivityV2.this, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                TokenInfo info = (TokenInfo)rspData;
                if (info.getRetcode() == 0) {
                    String token =  info.getData();
                    Config.setUserToken(token);
                    login();
                   /* Intent toIntent = new Intent(RegisterActivityV2.this, RegisterMobileActivity.class);
                    toIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Bundle bundle = new Bundle();
                    bundle.putString("UserName", userNameStr);
                    bundle.putString("Password", firstPasswordStr);
                    toIntent.putExtras(bundle);
                    startActivityForResult(toIntent, ACTIVITY_RESULT_REGISTER_MOBILE);*/
                } else {
                    Toast.makeText(RegisterActivityV2.this, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                    pd.dismiss();
                }
                hasSendTokenJson = false;
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(RegisterActivityV2.this, msg, Toast.LENGTH_SHORT).show();
                pd.dismiss();
                hasSendTokenJson = false;
            }
        }, TokenInfo.class);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_REGISTER_MOBILE) {
            Intent intent = new Intent();
            intent.putExtra("UserName", userNameStr);
            intent.putExtra("Password", firstPasswordStr);
            setResult(RESULT_OK, intent);
            RegisterActivityV2.this.finish();
        }
    }
    /**
     * 登录
     *
     */
    public void login() {
        pd.setMessage(getString(R.string.Is_landing));
        // pd.show();

        final long start = System.currentTimeMillis();
        // 调用sdk登陆方法登陆聊天服务器
        EMClient.getInstance().login(username, password, new EMCallBack() {

            @Override
            public void onSuccess() {
                if (!progressShow) {
                    return;
                }
                if (!hasSendGetUserJson) {
                    GetUserJson getUserJson = new GetUserJson(Config.getUserToken(),
                            username);
                    getUserByUsernameRequest(Constants.getUserByUsername,
                            getUserJson);
                }
                try {
                    // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                    // ** manually load all local groups and
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    // 处理好友和群组
                    initializeContacts();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 取好友或者群聊失败，不让进入主页面
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            DemoHXSDKHelper.getInstance().logout(true, null);
                            // 登录失败: 获取好友或群聊失败
                            Toast.makeText(getApplicationContext(),
                                    R.string.login_failure_failed, 1).show();
                        }
                    });
                    return;
                }

            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                if (!progressShow) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(),
                                getString(R.string.loginfail), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
    private void initializeContacts() {
        Map<String, FriendsUser> userlist = new HashMap<String, FriendsUser>();
        // 新的朋友
        FriendsUser newFriends = new FriendsUser(Constants.NEW_FRIENDS_USERNAME);
        //  newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
        String strChat = getResources()
                .getString(R.string.Application_and_notify);
        newFriends.setNickname(strChat);
        userlist.put(Constants.NEW_FRIENDS_USERNAME, newFriends);
        // 群聊
        FriendsUser groupUser = new FriendsUser(Constants.GROUP_USERNAME);
        String strGroup = getResources().getString(R.string.group_chat);
        //  groupUser.setUsername(Constant.GROUP_USERNAME);
        groupUser.setNickname(strGroup);
        groupUser.setHeader("");
        userlist.put(Constants.GROUP_USERNAME, groupUser);
        // 存入内存
        ((DemoHXSDKHelper) HXSDKHelper.getInstance()).setContactList(userlist);
        // 存入db
        UserDao dao = new UserDao(mContext);
        List<FriendsUser> users = new ArrayList<FriendsUser>(userlist.values());
        dao.saveContactList(users);
    }
    /**
     * 从服务器获取登录者的相关信息
     *
     * @param getUserByUsername
     * @param mGetUserJson
     */
    private void getUserByUsernameRequest(String getUserByUsername,
                                          GetUserJson mGetUserJson) {
        Log.i(TAG,
                "<getUserByUsernameRequest>--<onResponse>--上传的JSon数据：  GetUserJson = "
                        + mGetUserJson);
        hasSendGetUserJson = true;
        Type type = new TypeToken<BaseResult<getUserByUsernameBean>>() {
        }.getType();
        JsonListRequest<BaseResult<getUserByUsernameBean>> request = new JsonListRequest<BaseResult<getUserByUsernameBean>>(
                mContext, Request.Method.POST, getUserByUsername,
                mGetUserJson.toString(), null, null, type, false,
                new Response.Listener<BaseResult<getUserByUsernameBean>>() {

                    @Override
                    public void onResponse(
                            BaseResult<getUserByUsernameBean> arg0) {
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        getUserByUsernameBean data = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        if (code == Constants.SUCCESS) {
                            data = arg0.getData();
                            if (data != null) {
                                // 登陆成功，保存用户名密码
                                Config.setUserName(username);
                                Config.setPassword(password);

                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserAvatar(Constants.GETIMAGE
                                                + data.getImagepath());
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserSex(data.getSex());
                                if (null != data.getNickname()) {
                                    HXPreferenceUtils.getInstance()
                                            .setCurrentUserNick(
                                                    data.getNickname());
                                } else {
                                    HXPreferenceUtils.getInstance()
                                            .setCurrentUserNick(
                                                    data.getUsername());
                                }
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserSignature(
                                                data.getSignature());
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserBackground(
                                                Constants.GETIMAGE
                                                        + data.getBackphoto());
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserMobile(
                                                data.getTelphone());
                                // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {
                                        updatenick = EMClient.getInstance().pushManager()
                                                .updatePushNickname(
                                                        HXPreferenceUtils
                                                                .getInstance()
                                                                .getCurrentUserNick());
                                    }
                                }).start();

                                if (!updatenick) {
                                    Log.e("LoginActivity", HXPreferenceUtils
                                            .getInstance().getCurrentUserNick()
                                            + "----"
                                            + "update current user nick fail");
                                }
                                if (!RegisterActivityV2.this.isFinishing()
                                        && pd.isShowing()) {
                                    pd.dismiss();
                                }
                                Toast.makeText(mContext, getString(R.string.loginok),
                                        Toast.LENGTH_SHORT).show();
                                // 进入主页面
                                registerMobile();

                            }
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                            DemoHXSDKHelper.getInstance().logout(true, null);
                        }
                        pd.dismiss();
                        hasSendGetUserJson = false;
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                NetworkResponse response = arg0.networkResponse;
                if (response != null) {
                    try {
                        String json = new String(response.data,
                                HttpHeaderParser.parseCharset(
                                        response.headers));
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onErrorResponse> -- json = "
                                        + json);
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onErrorResponse> -- response.data = "
                                        + response.data);
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onErrorResponse> -- response.headers = "
                                        + response.headers);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                if (arg0 != null && arg0.toString().contains(
                        "com.android.volley.NoConnectionError")) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.ServerError")) {
                    Toast.makeText(mContext,
                            getString(
                                    R.string.service_temporarily_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.TimeoutError")) {
                    Toast.makeText(mContext,
                            getString(R.string.time_out_error),
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext,
                            getString(R.string.request_fail),
                            Toast.LENGTH_SHORT).show();
                }
                Log.i(TAG,
                        "<getUserByUsernameRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                + arg0);
                Log.i(TAG,
                        "<getUserByUsernameRequest>--<onErrorResponse>--服务器请求失败： response = "
                                + response);
                DemoHXSDKHelper.getInstance().logout(true, null);
                pd.dismiss();
                hasSendGetUserJson = false;
            }

        });
        VolleyUtil.addRequest(request);
    }

    private void registerMobile() {
        Intent toIntent = new Intent(RegisterActivityV2.this, RegisterMobileActivity.class);
        toIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Bundle bundle = new Bundle();
        bundle.putString("UserName", userNameStr);
        bundle.putString("Password", firstPasswordStr);
        toIntent.putExtras(bundle);
        startActivityForResult(toIntent, ACTIVITY_RESULT_REGISTER_MOBILE);
        finish();
    }
}
